﻿using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Nes4Core.UI
{
    public class AudioWaveProvider : IWaveProvider, IDisposable
    {
        private const Int32 SAMPLE_COUNT = 2048;

        private BufferedWaveProvider bufferedWaveProvider;
        private ISampleProvider sampleProvider;
        public Action ReadCallBack { get; set; }


        public AudioWaveProvider() 
        {
            bufferedWaveProvider = new BufferedWaveProvider(new WaveFormat(44100, 32 ,1));
            bufferedWaveProvider.DiscardOnBufferOverflow = true;
            bufferedWaveProvider.BufferLength = SAMPLE_COUNT;
            sampleProvider = bufferedWaveProvider.ToSampleProvider();
        }

        public WaveFormat WaveFormat => bufferedWaveProvider.WaveFormat;

        public void Dispose()
        {

        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Write(Double sample)
        {
            var buffss = BitConverter.GetBytes((Single)sample);
            bufferedWaveProvider.AddSamples(buffss, 0, buffss.Length);
        }

        public int Read(byte[] buffer, int offset, int count)
        {
            var len = bufferedWaveProvider.Read(buffer, offset, count);
            return len;
        }

        public int Read(float[] buffer, int offset, int count)
        {
            var len = sampleProvider.Read(buffer, offset, count);
            return len;
        }

    }
}
